<?php
/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

defined('AUTH_SERVICE') or define('AUTH_SERVICE', 'google');

require_once '../server.php';
require_once '../../library/googleapi/apiClient.php';

$client = new apiClient();
$client -> setApplicationName('Google About Me!');
$client -> setScopes(array(
    'http://www.google.com/m8/feeds/',
    'https://www.googleapis.com/auth/userinfo.profile',
    'https://www.googleapis.com/auth/userinfo.email'
));
// Documentation: http://code.google.com/apis/gdata/docs/2.0/basics.html
// Visit https://code.google.com/apis/console?api=contacts to generate your
// oauth2_client_id, oauth2_client_secret, and register your oauth2_redirect_uri.
$client -> setClientId(GOOGLE_KEY);
$client -> setClientSecret(GOOGLE_SECRET);
$client -> setRedirectUri(AUTH_BASE_URL . '/google/connect.php');

//$client->setDeveloperKey('insert_your_developer_key');

if (isset($_GET['code']))
{
    $client -> authenticate();
    $_SESSION['token'] = $client -> getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token']))
{
    $client -> setAccessToken($_SESSION['token']);
}

if (isset($_REQUEST['logout']))
{
    unset($_SESSION['token']);
    $client -> revokeToken();
}

if ($client -> getAccessToken())
{
    $req = new apiHttpRequest('https://www.googleapis.com/oauth2/v1/userinfo?alt=json');

    $val = $client -> getIo() -> authenticatedRequest($req);

    $data = json_decode($val -> getResponseBody(), 1);

    processCentralServiceResponseData($data);

    // The access token may have been updated lazily.
    // $_SESSION['token'] = $client -> getAccessToken();
}
else
{
    $auth = $client -> createAuthUrl();
}

if (isset($auth))
{
    header('location: ' . $auth);
}
else
{
    print "<a class=logout href='?logout'>Logout</a>";
}
